﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge.Video.DirectShow;
using AForge.Video;
using AForge.Imaging.Filters;
using AForge.Imaging;
using AForge.Vision.Motion;
using AForge;

namespace Aforge
{
    public partial class Form1 : Form
    {
        private FilterInfoCollection kameralar;
        private VideoCaptureDevice kamera;
        int hue_min = 0, hue_max = 360;
        public Form1()
        {
            InitializeComponent();
            comboBox2.SelectedIndex = 0;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            kameralar = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            foreach(FilterInfo yakalamaaygiti in kameralar)
            {
                comboBox1.Items.Add(yakalamaaygiti.Name);

                comboBox1.SelectedIndex = 0;




            }   
        }


        // Yaptığımız ayarlamara göre bu metod sürekli çalışıyor
        // yakalanan frameleri burda işleyebilirsiniz
        void kamera_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {   
                Bitmap image = (Bitmap)eventArgs.Frame.Clone();

                ResizeBilinear a = new ResizeBilinear(400, 300);
                Bitmap newImage = a.Apply(image);


                // Kamerada Görüntünün ters çıkmasını engelledik.
                newImage.RotateFlip(RotateFlipType.Rotate180FlipY);
                image.RotateFlip(RotateFlipType.Rotate180FlipY);


                //------------------------------------------------------
                // HSL Filtresi İle Kırmızı Nesneleri Çıkaralım
                // Hue : Renk Aralığı 0-360 arası 
                // Saturation : Doygunluk float olarak 0-1 arası
                // Luminance : Beyazlık değeri float 0-1 arası
                // Sensitivity ayarlamak size kalmış
                // BKZ : hslpicker.com
                //------------------------------------------------------


                HSLFiltering filter = new HSLFiltering();
                filter.Hue = new IntRange(hue_min, hue_max);
                filter.Saturation = new Range(0.5f, 1);
                filter.Luminance = new Range(0.3f, 1);
                filter.ApplyInPlace(newImage);


                BlobCounter blobCounter = new BlobCounter();
                blobCounter.MinWidth = 5;
                blobCounter.MinHeight = 5;
                blobCounter.MaxWidth = 250;
                blobCounter.MaxHeight = 250;
                blobCounter.FilterBlobs = true;
                blobCounter.ObjectsOrder = ObjectsOrder.Size;
                Grayscale grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
                Bitmap grayImage = grayFilter.Apply(newImage);
                blobCounter.ProcessImage(grayImage);
            
                Rectangle[] rects = blobCounter.GetObjectsRectangles();
                foreach (Rectangle recs in rects)
                {
                    if (rects.Length > 0)
                    {
                        Rectangle objectRect = rects[0];
                        //Graphics g = Graphics.FromImage(image);
                        Graphics g = picbox.CreateGraphics();
                        using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2))
                        {
                            g.DrawRectangle(pen, objectRect);
                        }
                        //Cizdirilen Dikdörtgenin Koordinatlari aliniyor.
                        int objectX = objectRect.X + (objectRect.Width / 2);
                        int objectY = objectRect.Y + (objectRect.Height / 2);
                       //int objectX = objectRect.X;
                       //int objectY = objectRect.Y;
                        mausecontrol(objectX, objectY);
                       // g.DrawString(objectX.ToString() + "X" + objectY.ToString(), new Font("Seogei", 12), Brushes.Red, new System.Drawing.Point(250, 1));
                        g.Dispose();

                    }
                }



 
            picbox.Image = image;
        }

        public void mausecontrol(int a, int b)
        {
            if (a > 650)
            {
                a = a + 650;
            }
            if (a < 650)
            {
                a = 650 - a;
            }
            Cursor.Position = new System.Drawing.Point((a * 21) / 10, ((b * 16) / 10));
        }

        // Butona bastığımızda yakalama nesnesi oluşuyor ve özellikleri ayarlanıyor
        // Ardından kamera çalışmaya başlıyor
        private void button1_Click(object sender, EventArgs e)
        { 
            int v = Convert.ToInt16(comboBox2.SelectedIndex); 

            if (v == 0)
            {
                hue_min = 345;
                hue_max = 10;
            }

            else if (v == 1)
            {
                hue_min = 200;
                hue_max = 260;
            }
            else if (v == 2) {
                hue_min = 85;
                hue_max = 135;
            }
            kamera = new VideoCaptureDevice(kameralar[comboBox1.SelectedIndex].MonikerString);
            kamera.DesiredFrameSize = new Size(640, 480);
            kamera.DesiredFrameRate = 20;
            kamera.NewFrame += new NewFrameEventHandler(kamera_NewFrame);
            kamera.Start();
            
        }


        // X e bastığımızda çalışan kamera duruyor
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(kamera.IsRunning){
                kamera.Stop();
            }
        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {

        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

    }
}
